<template>
  <a-modal width="700px" size="small" :bodyStyle="{ padding: '0 12px' }" destroyOnClose>
    <template #title>
      {{ gtitle }}
      <div style="margin-bottom: -16px;">
        <a-tabs v-model:activeKey="activeKey" size="small" :tabBarStyle="{ margin: 0 }">
          <a-tab-pane key="1" tab="接口代码/类型">
          </a-tab-pane>
          <a-tab-pane key="2" tab="相关JSON"></a-tab-pane>
        </a-tabs>
      </div>
    </template>
    <div class="code-content">
      <pre v-if="activeKey === '1'">
        <div v-html="code.html"></div>
      </pre>
      <pre v-if="activeKey === '2'">
        <div v-html="code.jsonc"></div>
      </pre>
    </div>
  </a-modal>
</template>
<script lang="ts">
import { activeCodeItem } from "@/settings/local";
import { computed, defineComponent, unref, ref, watch } from 'vue';
import hljs from "highlight.js/lib/common";
import "highlight.js/styles/vs.css";
import { getCode, getJson } from '../hooks/useGenCode';
export default defineComponent({
  props: {
    requireParams: {
      type: Array,
      default: () => [],
    },
    response: {
      type: Array,
      default: () => [],
    },
    requireMethod: {
      type: String,
      default: "GET",
    },
    url: {
      type: String,
      default: "",
    },
    summary: {
      type: String,
      default: "",
    },
    gtitle: String
  },
  setup(props) {
    const activeKey = ref("1")
    watch(()=>props.gtitle, ()=> activeKey.value = "1") // 更换对象重置为第一项

    const code = computed(() => {
      const content = unref(activeCodeItem).content || "";
      if (!props.url) {
        return {
          html: hljs.highlightAuto("no code ..", ["typescript"]).value,
          text: "",
        };
      }
      const codeOption = {
        url: props.url,
        method: props.requireMethod,
        summary: props.summary,
        params: props.requireParams,
        response: props.response
      };

      const code = getCode(codeOption, content);
      const jsonc = getJson(codeOption, content);

      return {
        html: hljs.highlightAuto(code as string, ["typescript"]).value,
        jsonc: hljs.highlightAuto(jsonc as string, ["typescript"]).value,
        text: code,
      };
    });

    return {
      code,
      activeKey
    };
  },
});
</script>
<style lang="less" scoped>
pre {
  word-wrap: break-word;
  white-space: pre-wrap;
}
.code-content{
  max-height: 60vh;
  overflow-y: auto;
}
</style>